<?php

namespace App\Services\Stats\User;

use App\Core\Traits\Numeral;
use App\Exports\Stats\User\PlayerBetExport;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Admin\Stats\PlayerBet\Hour as StatsHour;
use App\Models\Admin\Stats\PlayerBet\Day as StatsDay;
use App\Models\Admin\Stats\PlayerBet\Month as StatsMonth;
use Helper\Timed;

class PlayerBetService extends Service
{
    use DatabaseMysql, Numeral;

    /**
     * 导出数据
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return false|void
     */
    private function export($query, $request, bool $export)
    {
        if (!$export) {
            return false;
        }
        // 前端排序
        $this->makeOrderParam($request, $query);
        // 平台信息
        $query->with('org:code,name');
        // 导出文件
        PlayerBetExport::query($query)->setRequest($request)->download();
    }

    /**
     * 获取数据列表【小时】
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
     */
    public function hour($request, $export = false)
    {
        return $this->getList($request, StatsHour::query(), $export);
    }

    /**
     * 获取数据列表【天】
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
     */
    public function day($request, $export = false)
    {
        return $this->getList($request, StatsDay::query(), $export);
    }

    /**
     * 获取数据列表【月】
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
     */
    public function month($request, $export = false)
    {
        $datetime = $request->input('datetime');

        if (!empty($datetime)) {
            $request->merge(['datetime' => [
                Timed::getMonthCurrentTimed($datetime[0]),
                Timed::getMonthCurrentTimed($datetime[1]),
            ]]);
        }

        return $this->getList($request, StatsMonth::query(), $export);
    }

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
     */
    public function getList($request, $query, $export)
    {
        // 筛选【平台】
        $this->makeWhereParamOrg($request, $query);
        // 筛选【平台】【排除】
        $this->makeWhereParamNot($request, 'plat_code_exclude', $query, 'plat_code');
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query);
        // 筛选【币种】
        $this->makeWhereParam($request, 'currency', $query);
        // 筛选【币种】【排除】
        $this->makeWhereParamNot($request, 'currency_exclude', $query, 'currency');
        // 筛选【游戏】
        $this->makeWhereParam($request, 'game_id', $query);
        // 筛选【游戏】【排除】
        $this->makeWhereParamNot($request, 'game_id_exclude', $query, 'game_id');
        // 筛选【场景】
        $this->makeWhereParam($request, 'scene_id', $query);
        // 筛选【搜索】
        $this->makeWhereParamSearch($request, $query);

        // 导出数据
        $this->export($query, $request, $export);

        // 数据条数
        $total = (clone $query)->count();
        // 统计数据
        $stats = $this->getStats(clone $query);
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->with('org:code,name')->orderBy('uid')->get();

        return [
            $collection,
            $total,
            $stats
        ];
    }

    /**
     * 获取统计信息
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return array
     */
    private function getStats($query)
    {
        // USD
        $usd = (clone $query)->getQuery()->selectRaw(implode(',', [
            'IFNULL(SUM(doc_count),0) as doc_count',
            "IFNULL(CAST(SUM(usd->'$.amount') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS amount",
            "IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS gain_player",
            "IFNULL(CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_base",
            "IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_num",
        ]))->first();

        // 分币种
        $sts = $query->getQuery()->selectRaw(implode(',', [
            'IFNULL(SUM(doc_count),0) as doc_count',
            'IFNULL(SUM(amount),0) as amount',
            'IFNULL(SUM(gain_player),0) as gain_player',
            'IFNULL(SUM(bet_base),0) as bet_base',
            'IFNULL(SUM(bet_num),0) as bet_num',
            'currency',
        ]))
            ->groupBy('currency')
            ->get();

        return [
            'usd' => $usd,
            'sts' => $sts,
        ];
    }
}
